<template>
  <div class="product-upload">
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      :limit="1"
      drag
      :key="key"
      action="#"
      :http-request="httpRequest"
      :show-file-list="true"
      v-bind="$attrs"
      :class="props.classes"
      :auto-upload="false"
      :multiple="false"
    >
      <slot />
    </el-upload>
    <el-progress
      v-if="props.progress && progressPercent"
      :percentage="progressPercent"
      :width="128"
    />
  </div>
</template>

<script setup>
import { skuImport } from "./api";
import MD5 from "spark-md5";
const props = defineProps({
  type: { type: String, default: "img" }, // 上传类型
  limit: { type: Number, default: 1 },
  classes: { type: String, default: "" }, // el-upload的class
  validator: { type: Function, default: () => {} }, // 校验函数
  form: { type: Object },
  progress: Boolean, // 是否使用进度条
});

const emit = defineEmits(["success", "error"]);
const key = ref(0);
const progressPercent = ref(0);
watch(progressPercent, (val) => {
  if (val === 100) {
    const timer = setTimeout(() => {
      progressPercent.value = 0;
      clearTimeout(timer);
    }, 1000);
  }
});

const fileList = ref([]);

const httpRequest = (fileData) => {
  const { file } = fileData;
  // beforeUpload(file).then(fileInfo => {
  progressPercent.value = 0;
  let formData = new FormData();
  formData.append("skuXlsx", file);
  skuImport(formData).then((res) => {
    const spark = new MD5.ArrayBuffer();
    spark.append(file);
    emit("success", res.data);
  });
  // }).catch(e => {
  //   emit('error', e)
  // })
};

const uploadRef = ref();
const submitUpload = () => {
  uploadRef.value.submit();
};
const clearFiles = () => {
  uploadRef.value.clearFiles();
};

defineExpose({ submitUpload, clearFiles });
</script>

<style lang="scss" scoped>
.product-upload {
  :deep(.el-upload-dragger) {
    border-color: #3487ff;
  }
  :deep(.el-upload-list__item-file-name) {
    color: #3487ff;
  }
}
</style>
